<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS打字小游戏</title>
    <style>
        body {
            padding: 0px;
            margin: 0;
        }

        #gameStage {
            position: absolute;
            left: 0;
            width: 85%;
            height: 100%;
            background-color: aquamarine;
        }
        #scoreStage {
        position: absolute;
        right: 0;
        width: 15%;
        height: 100%;
        background-color: pink;
      }
      #options {
        position: relative;
        top: 50%;
        left: 20%;
      }
      /* 定义模态对话框外面的覆盖层样式 */
        #modal-overlay {
             visibility: hidden;
             position: absolute;   /* 使用绝对定位或固定定位  */
             left: 0px;
             top: 0px;
             width:100%;
             height:100%;
             text-align:center;
             z-index: 1000;
             background-color: #333;
             opacity: 0.5;   /* 背景半透明 */
        }
        /* 模态框样式 */
        .modal-data{
             width:300px;
             margin: 100px auto;
             background-color: #fff;
             border:1px solid #000;
             padding:15px;
             text-align:center;
        }
    </style>
</head>
<body>
<audio id = "bgm" src = "music/bgm.wav" autoplay="autoplay" loop = "loop">不支持该音乐格式</audio>
<audio id = "otherM"></audio>
<div id="gameStage"></div>
<div id = "scoreStage">
    <table id = "options">
        <tr><td>难度：</td><td id = "levelBlock"></td></tr>
        <tr><td>分数：</td><td id = "scoreBlock">0</td></tr>
        <!-- <tr><td></td></tr> -->
    </table>
</div>
<div id="modal-overlay">
    <div class="modal-data">
        <p>请选择游戏等级</p>
        难度：<select id='gameLevel'>
            <option value="low">简单</option>
            <option value="mid">中等</option>
            <option value="height">困难</option>
        </select>
        <p><input type="button" value="确定" onclick="director.start()" ></p>
    </div>
  </div>
<script>
  function overlay(){
      var e1 = document.getElementById('modal-overlay');
      if (e1.style.visibility == "visible") {
          e1.style.visibility = "hidden";
          gl = document.getElementById('gameLevel');
          console.log(gl.value);
      } else {
          e1.style.visibility = "visible"
      }
  }
  /**
   * 字母
   * @param id
   * @param alphabet
   * @param posX
   * @param posY
   * @param size
   * @constructor
   */
  function Word(id, alphabet, posX, posY, size) {

    //初始化数据
    this.id = id || '';
    this.alphabet = alphabet || 'a';
    this.posX = posX || 0;
    this.posY = posY || 0;
    this.size = size || 64;


    // 新建
    this.create = function () {
      var str = '<span class="word" id="alphabet-' + this.id + '">' + this.alphabet + '</span>';
      var gameStage = document.getElementById('gameStage');
      gameStage.innerHTML += str;

      var divNode = document.getElementById('alphabet-' + this.id);
      divNode.style.position = 'absolute';
      divNode.style.fontSize = this.size + 'px';
      divNode.style.left = this.posX + 'px';
      divNode.style.top = this.posY + 'px';

    };
    // 重置.
    this.reset = function () {
      var divNode = document.getElementById('alphabet-' + this.id);
      divNode.style.display = 'none';
      this.moveTo(0, 0);
    };

    // 移动到指定点
    this.moveTo = function (posX, posY) {
      this.posX = posX;
      this.posY = posY;

      var divNode = document.getElementById('alphabet-' + this.id);
      divNode.style.left = posX + 'px';
      divNode.style.top = posY + 'px';
    };
  }

  /**
   * 导演类
   */
  var director = {
    alphabets: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],

    nodes: new Array(),

    /**
     * 逐帧运行
     */
    runFrame: function () {

      //更新已经产生所有点的坐标
      for (var index in this.nodes) {
        var node = this.nodes[index];
        if (node) {
          node.moveTo(node.posX, node.posY + 5);
          if (node.posY > window.innerHeight) {
            director.end();
          }
        }
      }

      //随机产生字母
      var r = Math.floor(Math.random() * this.alphabets.length);
      var w = new Word(new Date().getTime(), this.alphabets[r]);

      w.create();
      this.nodes.push(w);

      var posX = Math.floor(Math.random() * window.innerWidth);
      //字母必须出现在游戏区域
      if (posX < 50) {
        posX = 100;
      }
      var gameStageMaxWidth = window.innerWidth * 0.8;
      if (posX >= gameStageMaxWidth - 100) {
        posX = gameStageMaxWidth - 100;
      }

      w.moveTo(posX, 0);
    },

    /**
     * 开始游戏
     */
    start: function () {
      var _this = this;

      var e1 = document.getElementById('modal-overlay');
      if (e1.style.visibility == "visible") {
          e1.style.visibility = "hidden";
          var gl = document.getElementById('gameLevel');

          //监听键盘事件
          document.onkeydown = function () {
            var alphabet = String.fromCharCode(event.keyCode); //获取键盘敲中的字母
            for (var i = 0, len = _this.nodes.length; i < len; i++) {
              if(!_this.nodes[i]) {
                continue;
              }
              if (alphabet === _this.nodes[i].alphabet) { //键盘和字幕匹配得分
                _this.nodes[i].reset();
                scoreCounter.incScore();
                _this.nodes[i] = null;
              }
            }
          };

          var frameRate = 0;
          console.log(gl.value);
          var lb = document.getElementById("levelBlock");
          //游戏主循环
          switch (gl.value) {
            case "low": frameRate = 100; lb.innerHTML = "简单"; break;
            case "mid": frameRate = 85;  lb.innerHTML = "中等"; break;
            case "height": frameRate = 50;  lb.innerHTML = "困难"; break;
            default : frameRate = 100;  lb.innerHTML = "简单"; break;
          }
          console.log(frameRate);
          timerNum = setInterval(function () {
            _this.runFrame();
          },frameRate);
      } else {
          e1.style.visibility = "visible"
      }

    },
    /**
     * 结束游戏
     */
     end: function() {
        Music.pause();
        Music.play("music/fail.wav");
        clearInterval(timerNum);
        window.setTimeout("window.location.reload();",3000);
     }
  }

  /**
   * 计分器
   */
  var scoreCounter = {
    score: 0,
    incScore: function () {
      this.score++;
      var sb = document.getElementById('scoreBlock');
      sb.innerHTML = this.score;
      Music.play("music/right.wav");
    },
    getScore: function () {
      return this.score;
    }
  };
  /**
   * 音乐播放
   */
  var Music = {

    play: function(src) {
      var m = document.getElementById("otherM");
      m.src = src;
      m.load();
      m.play();

    },
     pause: function() {
      var bgmTag = document.getElementById("bgm");
      bgmTag.pause();
    },
    // playBgm: function() {
    //   var bgmTag = document.getElementById("bgm");
    //   bgmTag.play();
    // }
  }
  /**
   * 难度选择
   */

  director.start();
  // console.log(window.innerWidth + "---" + window.innerHeight);
</script>
</body>
</html>